package com.du.javaweb.servlet; /**
 * @author : DuJiabao
 * @Date : 2021/3/28 15:38
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc :
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UpdateCookieServlet", value = "/UpdateCookieServlet")
public class UpdateCookieServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter writer = response.getWriter();
    Cookie cookie = CookieUtils.findCookie("key", request.getCookies());

    if (cookie == null) {
      writer.write("未找到，创建一个新的cookie <br/>");
      cookie = new Cookie("key", "value");
    }

    System.out.println(cookie.getName() + " : " + cookie.getValue());
    // 修改cookie的值
    cookie.setValue("value2");
    System.out.println(cookie.getName() + " : " + cookie.getValue());
    //设置cookie的生命长度（秒为单位）
    cookie.setMaxAge(100);
    //cookie.setMaxAge(3);
    //cookie.setMaxAge(0);
    //cookie.setMaxAge(-1);

    // 设置Cookie的有效路径
    cookie.setPath(request.getContextPath() + "/UpdateCookieServlet");
    String path = cookie.getPath();
    writer.write(path + "<br/>");

    // 将cookie通过响应，返回给客户端
    response.addCookie(cookie);
    writer.write("修改完毕 <br/>");
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
}
